package com.ly.common.core.tool.security.filter;

import com.ly.common.core.tool.security.config.properties.TokenProperties;
import com.ly.common.core.tool.security.entity.LyUser;
import com.ly.common.core.tool.security.utils.SecurityUtils;
import com.ly.common.core.tool.security.utils.TokenUtils;
import com.ly.common.core.utils.BaseUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 */
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final TokenProperties tokenProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader(tokenProperties.getHeader());
        if (token != null) {
            LyUser lyUser = BaseUtils.getLoginUser();
            if (lyUser != null && SecurityUtils.getAuthentication() == null) {
                // Token 续期
                TokenUtils.verifyToken(lyUser);
                // 获取认证信息，设置上下文
                UsernamePasswordAuthenticationToken token1 = new UsernamePasswordAuthenticationToken(lyUser, null, lyUser.getAuthorities());
                token1.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(token1);
            }
        }
        chain.doFilter(request, response);
    }
}
